/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-2-16 下午6:45
 */

package com.lenovo.mso2o.ui;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.DialogFragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lenovo.framework.FApplication;
import com.lenovo.framework.base.ActionBarFragmentActivity;
import com.lenovo.framework.base.BaseActionBarMockingActivity;
import com.lenovo.framework.base.BaseDialogFragment;
import com.lenovo.framework.base.InjectableFragmentActivity;
import com.lenovo.framework.biz.ContextManager;
import com.lenovo.framework.conf.FConstants;
import com.lenovo.framework.entity.Res;
import com.lenovo.framework.rest.NetworkObserver;
import com.lenovo.framework.rx.RxBus;
import com.lenovo.framework.util.image.CircleTransform;
import com.lenovo.framework.util.DLog;
import com.lenovo.framework.util.FPreferenceManager;
import com.lenovo.mso2o.BuildConfig;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.biz.AccountManagerImpl;
import com.lenovo.mso2o.conf.BizErrorCode;
import com.lenovo.mso2o.conf.ErrorCode;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.entity.GrabResult;
import com.lenovo.mso2o.rest.OrderAPI;
import com.lenovo.mso2o.rest.OtherAPI;
import com.lenovo.mso2o.rest.ServiceGenerator;
import com.lenovo.mso2o.service.AutoSignService;
import com.lenovo.mso2o.service.UploadService;
import com.lenovo.mso2o.ui.adapter.MainTabPagerAdapter;
import com.lenovo.mso2o.ui.adapter.NavigationViewAdapter;
import com.lenovo.mso2o.ui.fragment.AboutFragment;
import com.lenovo.mso2o.ui.fragment.AppModifyPassFragment;
import com.lenovo.mso2o.ui.fragment.AppSettingFragment;
import com.lenovo.mso2o.ui.fragment.AutoSignFragment;
import com.lenovo.mso2o.ui.fragment.HistoryOrderFragment;
import com.lenovo.mso2o.ui.fragment.NotificationFragment;
import com.lenovo.mso2o.ui.fragment.OrderFilterFragment;
import com.lenovo.mso2o.ui.fragment.OrderGrabListFragment;
import com.lenovo.mso2o.ui.fragment.OrderReceivingFragment;
import com.lenovo.mso2o.ui.fragment.POIMarkerFragment;
import com.lenovo.mso2o.util.PrefExtraUtils;
import com.lenovo.mso2o.util.Utils;
import com.lenovo.mso2o.view.TabSelectListener;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateConfig;
import com.umeng.update.UpdateResponse;

import butterknife.Bind;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class MainActivity extends BaseActionBarMockingActivity
        implements ViewPager.OnPageChangeListener, AdapterView.OnItemClickListener, UmengUpdateListener {
    public static final String OPEN_NOTIFICATION = "open_notification";
    public static final String OPEN_RECEIVING = "open_receiving";
    public static final String OPEN_GRAB = "open_grab";
    public static final String OPEN_FILTER = "open_filter";
    public static final String MAIN_FINISH = "main_finish";
    public static final String OPEN_ORDER_SIGN = "open_order_sign";

    public static final int PAGE_INDEX_PAGE = 0;
    public static final int PAGE_ACTIVE_ORDER = 1;
    public static final int PAGE_HISTORY_ORDER = 2;
    public static final int PAGE_SYSTEM_MESSAGE = 1;
    private RxBus rxBus;

    MainTabPagerAdapter mPagerAdapter;
    @Bind(R.id.viewpager)
    ViewPager viewPager;
    @Bind(R.id.tablayout)
    TabLayout tabLayout;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawer;
    @Bind(R.id.nav_view)
    NavigationView navigationView;
    @Bind(R.id.actionbar_left)
    ImageView menuIcon;
    @Bind(R.id.actionbar_left_layout)
    RelativeLayout left_layout;
    @Bind(R.id.actionbar_right_status)
    FrameLayout frameStatusLayout;

    private int position;
    private View statusDropDownView;
    private PopupWindow mPopWindow;
    private NavigationViewAdapter navigationViewAdapter;
    private boolean exit = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!AccountManagerImpl.instance.checkIn(this)) {
            finish();
            return;
        }
        rxBus = FApplication.getRxBus();
        initRxEvent();

        initPager();
        initNavigation();

        UmengUpdateAgent.setUpdateOnlyWifi(false);
        UmengUpdateAgent.setDeltaUpdate(true);
        UmengUpdateAgent.setUpdateAutoPopup(true);
        UmengUpdateAgent.setRichNotification(true);
        UmengUpdateAgent.update(this);
        UpdateConfig.setDebug(BuildConfig.DEBUG);

        if (AccountManagerImpl.instance.isLogin()) {
            AccountManagerImpl.async();
        }
        getIntent().putExtra(MainActivity.MAIN_FINISH, false);
        overridePendingTransition(0, 0);
        onNewIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            DLog.i("newintent", intent.getExtras() == null ? "null" : intent.getExtras().toString());
            boolean openNotify = intent.getBooleanExtra(MainActivity.OPEN_NOTIFICATION, false);
            boolean openReceiving = intent.getBooleanExtra(MainActivity.OPEN_RECEIVING, false);
            boolean openGrab = intent.getBooleanExtra(MainActivity.OPEN_GRAB, false);
            boolean openFilter = intent.getBooleanExtra(MainActivity.OPEN_FILTER, false);
            boolean openOrderSign = intent.getBooleanExtra(MainActivity.OPEN_ORDER_SIGN, false);
            if (openNotify) {
                FPreferenceManager.putInt(AccountManagerImpl.KEY_MAIN_PAGE, 3);
                onPageSelected(3, false);
                if (mPagerAdapter.getItem(3) != null)
                    ((NotificationFragment) mPagerAdapter.getItem(3)).loadData(1);
                //todo notifyId
            } else if (openReceiving) {
                FPreferenceManager.putInt(AccountManagerImpl.KEY_MAIN_PAGE, 0);
                onPageSelected(0, false);
                Bundle bundle = new Bundle();
                bundle.putInt(ActionBarFragmentActivity.FRAGMENT_TITLE, R.string.receive_order_pool);
                bundle.putString(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, OrderReceivingFragment.class.getName());
                bundle.putBoolean(ActionBarFragmentActivity.RIGHT_ACTIONBAR_ENABLE, true);
                bundle.putBoolean(ActionBarFragmentActivity.BACK_REFRESHABLE, true);
                openActivity(ActionBarFragmentActivity.class, bundle);
            } else if (openGrab) {
                FPreferenceManager.putInt(AccountManagerImpl.KEY_MAIN_PAGE, 0);
                onPageSelected(0, false);
                Bundle bundle = new Bundle();
                bundle.putString(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, OrderGrabListFragment.class.getName());
                bundle.putBoolean(ActionBarFragmentActivity.BACK_REFRESHABLE, true);
                bundle.putInt(MSConstants.FragmentType.FRAGMENT_ORDERTYPE, MSConstants.FragmentType.FRAGMENT_GRABORDERS);
                bundle.putInt(ActionBarFragmentActivity.FRAGMENT_TITLE, R.string.grab_activity_title);
                bundle.putBoolean(ActionBarFragmentActivity.RIGHT_ACTIONBAR_ENABLE, true);
                bundle.putBoolean(ActionBarFragmentActivity.BACK_REFRESHABLE, true);
                openActivity(ActionBarFragmentActivity.class, bundle);
            } else if (openFilter) {
                FPreferenceManager.putInt(AccountManagerImpl.KEY_MAIN_PAGE, 1);
                onPageSelected(1, true);
            } else if (openOrderSign) {
                FPreferenceManager.putInt(AccountManagerImpl.KEY_MAIN_PAGE, 1);
                onPageSelected(1, true);
                //打开活动工单的同时如果检测 自动签到数据库 暂且直接打开AutoSignFragment吧
                DialogFragment search = AutoSignFragment.getAutoSignInstance();
                if (search.isAdded() || search.isResumed()) {
                    search.dismiss();
                    search.onDestroy();
                    search = null;
                }
                search = AutoSignFragment.getAutoSignInstance();
                Bundle b = new Bundle();
                b.putBoolean(BaseDialogFragment.DISMISSABLE, true);
                //b.putString(SearchToolbarDialogFragment.TYPE_KEY, "site");
                search.setArguments(b);
                search.show(this.getSupportFragmentManager(), AutoSignFragment.TAG);
            }
        }
    }

    private void initRxEvent() {
        rxBus.toObserverable()
                //observable using rx activity bind to it's lifecycle!!!!!!!
                .compose(bindToLifecycle())
                .subscribe(new Action1<Object>() {
                    @Override
                    public void call(Object event) {
                        if (event.equals(UploadService.REFRESH_TOTAL_UPLOADING_MB)) {
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (navigationViewAdapter != null) {
                                        navigationViewAdapter.notifyDataSetChanged();
                                    }
                                }
                            });
                        } else {
                            String eventStr = event.toString();
                            if (AutoSignService.OPEN_ORDER_AND_SIGN.equals(eventStr)) {
                                FPreferenceManager.putInt(AccountManagerImpl.KEY_MAIN_PAGE, 1);
                                initPager();
                                if (mPagerAdapter.getItem(1) != null)
                                    ((OrderFilterFragment) mPagerAdapter.getItem(1)).onRefresh(true);
                                //打开活动工单的同时如果检测 自动签到数据库 暂且直接打开AutoSignFragment吧
                                DialogFragment search = AutoSignFragment.getAutoSignInstance();
                                Bundle b = new Bundle();
                                b.putBoolean(BaseDialogFragment.DISMISSABLE, true);
                                //b.putString(SearchToolbarDialogFragment.TYPE_KEY, "site");
                                search.setArguments(b);
                                search.show(MainActivity.this.getSupportFragmentManager(), AutoSignFragment.TAG);
                            }
                        }
                    }
                });
    }

    private void initNavigation() {
        LayoutInflater inflater = LayoutInflater.from(this);
        final View headerview = inflater.inflate(R.layout.nav_header_main, null);
        ImageView headerIcon = (ImageView) headerview.findViewById(R.id.iv_header_icon_nav_view);
        Glide.with(this)
                .load(R.drawable.header_icon_default)
                .transform(new CircleTransform(getApplicationContext()))
                .into(headerIcon);
        headerview.findViewById(R.id.nav_header_ripplelayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*
                Bundle bundle = new Bundle();
                bundle.putString(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, ProfileFragment.class.getName());
                bundle.putInt(ActionBarFragmentActivity.FRAGMENT_TITLE, R.string.title_user_profile);
                Intent intent = new Intent(MainActivity.this, ActionBarFragmentActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                */
            }
        });

        ListView navListView = (ListView) headerview.findViewById(R.id.nav_listView);
        navigationViewAdapter = new NavigationViewAdapter(null);
        navListView.setAdapter(navigationViewAdapter);
        navListView.setOnItemClickListener(this);
        /*if (CompatHelper.hasIceCreamSandwich()) {//王远指示，这一段不要了
            OverScrollDecoratorHelper.setUpOverScroll(navListView);
        }*/
        navigationView.addView(headerview);
        left_layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                final float menuWidth = left_layout.getLayoutParams().width;
                final float drawerWidth = drawer.getLayoutParams().width;
                drawer.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
                    @Override
                    public void onDrawerSlide(View drawerView, float slideOffset) {
                        super.onDrawerSlide(drawerView, slideOffset);
                        float radio = slideOffset * drawerWidth / menuWidth;
                        menuIcon.setRotation((radio > 1 ? 1 : radio) * 90 * 18);
                    }

                    @Override
                    public void onDrawerClosed(View drawerView) {
                        drawer.setTag(false);
                    }

                    @Override
                    public void onDrawerOpened(View drawerView) {
                        drawer.setTag(true);
                    }

                    @Override
                    public void onDrawerStateChanged(int newState) {
                        navigationViewAdapter.notifyDataSetChanged();
                        TextView tv_userName;
                        TextView tv_userProperty;
                        tv_userName = (TextView) headerview.findViewById(R.id.tv_userName);
                        tv_userProperty = (TextView) headerview.findViewById(R.id.tv_userJob);
                        tv_userProperty.setText(PrefExtraUtils.getString(MSConstants.UserInfoConstance.USER_NAME, ""));
                        tv_userName.setText(PrefExtraUtils.getString(MSConstants.UserInfoConstance.USER_ACCOUNT, ""));
                        tv_userName.setText("罗工");
                        tv_userProperty.setText("ID:2537849783");
                    }
                });
                //remove this!!
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    left_layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    left_layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });


        statusDropDownView = this.getLayoutInflater().inflate(R.layout.activity_popupwindow, null);
        mPopWindow = new PopupWindow(statusDropDownView, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置点击popupwindow外部，popupwindow消失
        mPopWindow.setTouchable(true);
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
    }

    private void initPager() {
        // Get the ViewPager and set it's PagerAdapter so that it can display items
        mPagerAdapter = new MainTabPagerAdapter(getSupportFragmentManager(), this);
        viewPager.setAdapter(mPagerAdapter);
        viewPager.addOnPageChangeListener(this);
        viewPager.setOffscreenPageLimit(3);

        // Give the TabLayout the ViewPager
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setSelectedTabIndicatorHeight(0);
        tabLayout.setOnTabSelectedListener(new TabSelectListener(viewPager));

        position = FPreferenceManager.getInt(AccountManagerImpl.KEY_MAIN_PAGE, 0);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            tabLayout.getTabAt(i).setCustomView(getTabItemView(i, i == position));
        }
        viewPager.setCurrentItem(position, false);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected String getActionBarTitleString() {
        /*if(position == 2){
            return null;
        }else {
        */
        return position == 0 ? "" : MainTabPagerAdapter.mTextviewArray[position];
        // }
    }

    public String getRightTitle() {
        return getString(R.string.historyorder);
    }

    public String getLeftTitle() {
        return getString(R.string.historyorders_totalanalysist);
    }

    @Override
    protected int getActionBarRightResourceId() {
        if (position == 1) {
            return R.drawable.icon_order_marker;
        } else if (position == 2) {
            Boolean isChecked = (Boolean) getTitleRight().getTag();
            if (isChecked != null && isChecked)
                return R.drawable.icon_search;
        }
        return 0;
    }


    @Override
    protected void onActionBarRightClick() {
        if (position == 0) {
        } else if (position == 1) {
            Intent intent = new Intent(this, ActionBarFragmentActivity.class);
            intent.putExtra(ActionBarFragmentActivity.FRAGMENT_TITLE, R.string.map_live_order);
            intent.putExtra(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, POIMarkerFragment.class.getName());
            intent.putExtra(MSConstants.FragmentType.class.getName(), MSConstants.FragmentType.FRAGMENT_ACTIVORDERS);
            startActivity(intent);
            /*
            getIntent().putExtra(FConstants.X5WEBVIEW_INITIAL_URL,
                    MSConstants.APIConstants.FAST_BILLING_URL);
            openActivity(WebActivity.class, getIntent().getExtras());
            */
        } else if (position == 2) {
            triggerSearchUi(true);
        }
    }

    //设置在线状态
    @Override
    protected void onActionBarRightStatusClick() {
        final ImageView iv = (ImageView) findViewById(R.id.iv_on_line);
        final TextView tv = (TextView) findViewById(R.id.tv_on_line);
        //弹出popupwindow
        if (mPopWindow.isShowing()) {
            mPopWindow.dismiss();// 关闭popupwindow
        } else {
            mPopWindow.showAsDropDown(frameStatusLayout);// 显示popupwindow
            //设置在线状态图片、文字、文字颜色
            statusDropDownView.findViewById(R.id.ll_pw_online).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopWindow.dismiss();
                    iv.setImageResource(R.drawable.home_page_on_line);
                    tv.setText(R.string.available);
                    tv.setTextColor(getResources().getColor(R.color.home_page_status_on_line_text_color));
                }
            });
            statusDropDownView.findViewById(R.id.ll_pw_busy).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopWindow.dismiss();
                    iv.setImageResource(R.drawable.home_page_busy);
                    tv.setText(R.string.busy);
                    tv.setTextColor(getResources().getColor(R.color.home_page_status_busy_text_color));
                }
            });
            statusDropDownView.findViewById(R.id.ll_pw_offline).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopWindow.dismiss();
                    iv.setImageResource(R.drawable.home_page_off_line);
                    tv.setText(R.string.offline);
                    tv.setTextColor(getResources().getColor(R.color.home_page_status_off_line_text_color));
                }
            });
        }
    }

    private View getTabItemView(int index, boolean selected) {
        View item = tabLayout.getTabAt(index).getCustomView();
        if (item == null) {
            item = View.inflate(this, R.layout.tab_item_view, null);
        }
        item.findViewById(R.id.imageviewblue).setVisibility(View.GONE);
        item.findViewById(R.id.textview_blue).setVisibility(View.GONE);

        ImageView imageView = (ImageView) item.findViewById(R.id.imageview);
        imageView.setImageResource(mPagerAdapter.getPageIcon(index, selected));

        TextView textView = (TextView) item.findViewById(R.id.textview);
        textView.setText(mPagerAdapter.getPageTitle(index));
        //选中的话白色前端未选中的textview不显示
        if (selected) {
            item.findViewById(R.id.textview_blue).setVisibility(View.VISIBLE);
            ((TextView) item.findViewById(R.id.textview_blue)).setTextColor(getResources().getColor(R.color.tab_item_text_selected_color));
            ((TextView) item.findViewById(R.id.textview_blue)).setText(mPagerAdapter.getPageTitle(index));
        }
        return item;
    }

    public void onPageSelected(int position, boolean refresh) {
        viewPager.setCurrentItem(position, false);
        onPageSelected(position);
        if (refresh) {
            if (position == PAGE_ACTIVE_ORDER)
                ((OrderFilterFragment) (mPagerAdapter.getItem(1))).onRefresh(true);
            else if (position == PAGE_HISTORY_ORDER)
                ((HistoryOrderFragment) (mPagerAdapter.getItem(2))).selectHistoryListAndRefresh();
        }
    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            tabLayout.getTabAt(i).setCustomView(getTabItemView(i, i == position));
        }

        this.position = position;
        FPreferenceManager.putInt(AccountManagerImpl.KEY_MAIN_PAGE, position);
        updateTitle();
        updateRightBtn();
        updateRight2Btn();
        if (this.position != 2) {
            triggerSearchUi(false);
        }
    }

    @Override
    protected int getActionBarRight2ResourceId() {
        return 0;
    }

    public void onActionBarRight2Click() {
        /*
        if(this.position == 1) {
            Intent intent = new Intent(this, ActionBarFragmentActivity.class);
            intent.putExtra(ActionBarFragmentActivity.FRAGMENT_TITLE, R.string.map_live_order);
            intent.putExtra(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, POIMarkerFragment.class.getName());
            intent.putExtra(MSConstants.FragmentType.class.getName(), MSConstants.FragmentType.FRAGMENT_ACTIVORDERS);
            startActivity(intent);
        }
        */
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        if (positionOffset > 0) {
            ImageView norLeft = (ImageView) tabLayout.getTabAt(position).getCustomView().findViewById(R.id.imageview);
            norLeft.setImageResource(mPagerAdapter.getPageIcon(position, false));
            ImageView norRight = (ImageView) tabLayout.getTabAt(position + 1).getCustomView().findViewById(R.id.imageview);
            norRight.setImageResource(mPagerAdapter.getPageIcon(position + 1, false));
            TextView leftText = (TextView) tabLayout.getTabAt(position).getCustomView().findViewById(R.id.textview_blue);
            TextView rightText = (TextView) tabLayout.getTabAt(position + 1).getCustomView().findViewById(R.id.textview_blue);
            ImageView left = (ImageView) tabLayout.getTabAt(position).getCustomView().findViewById(R.id.imageviewblue);
            ImageView right = (ImageView) tabLayout.getTabAt(position + 1).getCustomView().findViewById(R.id.imageviewblue);
            left.setVisibility(View.VISIBLE);
            right.setVisibility(View.VISIBLE);
            leftText.setVisibility(View.VISIBLE);
            rightText.setVisibility(View.VISIBLE);
            left.setImageResource(mPagerAdapter.getPageIcon(position, true));
            right.setImageResource(mPagerAdapter.getPageIcon(position + 1, true));
            left.setAlpha(1 - positionOffset);
            right.setAlpha(positionOffset);
            leftText.setTextColor(getResources().getColor(R.color.tab_item_text_selected_color));
            rightText.setTextColor(getResources().getColor(R.color.tab_item_text_selected_color));
            leftText.setText(mPagerAdapter.getPageTitle(position));
            rightText.setText(mPagerAdapter.getPageTitle(position + 1));
            leftText.setAlpha(1 - positionOffset);
            rightText.setAlpha(positionOffset);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    protected void onActionBarLeftClick() {
        drawer.openDrawer(GravityCompat.START);
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
            return;
        }
        if (isSearching()) {
            triggerSearchUi(false);
            return;
        }
        if (exit) {
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);
        } else {
            showShortToast(R.string.press_again_exit);
            exit = true;
            new Handler(Looper.getMainLooper())
                    .postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            exit = false;
                        }
                    }, 2000);
        }
    }

    protected void onTitleLeftClick() {
        ((HistoryOrderFragment) (mPagerAdapter.getItem(2))).replaceLeftFragment(this);
        getTitleRight().setTag(false);
        updateRightBtn();
    }

    protected void onTitleRightClick() {
        ((HistoryOrderFragment) (mPagerAdapter.getItem(2))).replaceRightFragment(this);
        getTitleRight().setTag(true);
        updateRightBtn();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) {
            //   openActivity(ChatAllHistoryFragmentActivity.class);
            //} else if (position == 1) {
            //设置
            Bundle bundle = new Bundle();
            bundle.putString(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, AppSettingFragment.class.getName());
            bundle.putInt(ActionBarFragmentActivity.FRAGMENT_TITLE, R.string.app_settings);
            openActivity(ActionBarFragmentActivity.class, bundle);
        /*} else if (position == 2) {
            Bundle bundle = new Bundle();
            bundle.putString(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, AppModifyPassFragment.class.getName());
            bundle.putInt(ActionBarFragmentActivity.FRAGMENT_TITLE, R.string.app_modify_password);
            openActivity(ActionBarFragmentActivity.class, bundle);
            */
        } else if (position == 2) {
            //修改密码
            Bundle bundle = new Bundle();
            bundle.putString(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, AppModifyPassFragment.class.getName());
            bundle.putInt(ActionBarFragmentActivity.FRAGMENT_TITLE, R.string.app_modify_password);
            openActivity(ActionBarFragmentActivity.class, bundle);
        } else if (position == 3) {
            //关于
            //this.<Res<GrabResult>>bindToLifecycle()
            /*Intent intent = new Intent(ContextManager.context(), WebActivity.class);
            intent.putExtra(FConstants.X5WEBVIEW_INITIAL_URL, MSConstants.APIConstants.APISERVER_ABOUT);
            startActivity(intent);*/

            /*Bundle bundle = new Bundle();
            bundle.putString(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, AboutFragment.class.getName());
            //bundle.putInt(ActionBarFragmentActivity.FRAGMENT_TITLE, );
            openActivity(ActionBarFragmentActivity.class, bundle);*/

            /*FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            //然后，你能够使用add()方法把Fragment添加到指定的视图中，如：
            AboutFragment fragment = new AboutFragment();
            fragmentTransaction.add(R.id.fragment_container, fragment);
            fragmentTransaction.commit();*/

            Intent intent = new Intent(this, InjectableFragmentActivity.class);
            intent.putExtra(InjectableFragmentActivity.FRAGMENT_CLASS_NAME, AboutFragment.class.getName());
            startActivity(intent);
        } else if (position == 4) {
            AccountManagerImpl.instance.reLogin();
        }
    }

    public void finish() {
        getIntent().putExtra(MAIN_FINISH, true);
        super.finish();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //DLog.i(getClass().getName(), " requestcode:" + requestCode + " resultcode:" + resultCode + " data:" + data == null ? "null" : data.getExtras() + "");
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case MSConstants.FragmentType.FRAGMENT_ACTIVORDERS:
                case MSConstants.FragmentType.FRAGMENT_GRABORDERS:
                case MSConstants.FragmentType.FRAGMENT_RECEIVEORDERS:
                    ((OrderFilterFragment) (mPagerAdapter.getItem(1))).onRefresh(false);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onUpdateReturned(int i, UpdateResponse updateResponse) {
        if (updateResponse != null && updateResponse.hasUpdate) {
            UmengUpdateAgent.downloadedFile(this, updateResponse);
        }
    }

    public int currIdx() {
        return position;
    }
}


